package com.sxfq.loansupermarket.backsystem.modular.marketing.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.constant.tips.Tip;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Role;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.PayServiceInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsAggregateInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.SearchReservationsAggregateInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.service.IReservationsAggregateService;
import com.sxfq.loansupermarket.backsystem.modular.system.transfer.UserDto;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.AddVisitedInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.service.IConsultantService;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 预约客户信息
 *
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/reservationsAggregate")
public class ReservationsAggregateController extends BaseController {

    @Autowired
    IReservationsAggregateService reservationsAggregateService;

    @Autowired
    ICustomerService customerService;

    @Autowired
    IConsultantService service;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/marketing/reservations/";

    /**
     * 跳转到预约客户管理页面
     */
    @RequestMapping("")
    public String reservationsAggregate(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "/reservationsAggregate.html";
    }

    /**
     * 预约客户管理列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object testrInfoList(SearchReservationsAggregateInfo info, HttpServletRequest request) {
        Page<ReservationsAggregateInfo> page = new PageFactory<ReservationsAggregateInfo>().defaultPage();
        try {
            List<ReservationsAggregateInfo> list = new ArrayList<ReservationsAggregateInfo>();
            list = reservationsAggregateService.selectPageListByQueryGetMap(page, info);
            if (list.size() == 0) {
                page.setCurrent(1);
                list = reservationsAggregateService.selectPageListByQueryGetMap(page, info);
            }
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    public String getTableName() {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return tableName;
    }

    @RequestMapping("/sumBorrowAmount")
    @ResponseBody
    public HashMap sumBorrowAmount(@RequestParam(required = false) String customerName,
                                   @RequestParam(required = false) String customerPhone,
                                   @RequestParam(required = false) String archiving,
                                   @RequestParam(required = false) String department,
                                   @RequestParam(required = false) String startTime,
                                   @RequestParam(required = false) String endTime,
                                   @RequestParam(required = false) String startArrivalTime,
                                   @RequestParam(required = false) String endArrivalTime,
                                   @RequestParam(required = false) String arrivalStore,
                                   @RequestParam(required = false) String reservationsNum,
                                   @RequestParam(required = false) String oneChannel,
                                   @RequestParam(required = false) String twoChannel,
                                   @RequestParam(required = false) String thrChannel,
                                   @RequestParam(required = false) String wechatNumber) {
        String sql = "    select sum(t1.money) as borrowAmount_sum from ( select\n" +
                "        t.id as id, t.customer_name as customerName,t.first_visit_date as firstVisitDate, t.customer_phone as\n" +
                "        customerPhone, t.customer_sex as customerSex, t.filing_time as filingTime,\n" +
                "        t.customer_age as customerAge, t.wechat_number as wechatNumber,t.archiving as archiving,\n" +
                "        t.one_medium as oneMedium, t.two_medium as twoMedium, t.thr_medium as thrMedium,t.reservations_num as\n" +
                "        reservationsNum,\n" +
                "        t.one_channel as oneChannel, t.two_channel as twoChannel, t.thr_channel as thrChannel ,\n" +
                "        t1.arrival_store as arrivalStore,t1.tc_name as tcName,t1.doctor as doctor,t1.department as department,t1.get_time as getTime\n" +
                "        ,t1.money as money\n" +
                "        from reservations_aggregate_info t1 left join  reservations_info t on t.id=t1.reservations_id\n" +
                "        where 1=1 ";
        if (StringUtil.isNotEmpty(customerName)) {
            sql += " and t.customer_name = '" + customerName + "'";
        }
        if (StringUtil.isNotEmpty(customerPhone)) {
            sql += " and t.customer_phone = '" + customerPhone + "'";
        }
        if (StringUtil.isNotEmpty(archiving)) {
            sql += " and t.archiving = '" + archiving + "'";
        }
        if (StringUtil.isNotEmpty(department)) {
            sql += " and t1.department = '" + department + "'";
        }
        if (StringUtil.isNotEmpty(startTime)) {
            sql += " and t1.get_time >= '" + startTime + "'";
        }
        if (StringUtil.isNotEmpty(endTime)) {
            sql += " and t1.get_time <= '" + endTime + "'";
        }
        if (StringUtil.isNotEmpty(startArrivalTime)) {
            sql += " and t.first_visit_date >= '" + startArrivalTime + "'";
        }
        if (StringUtil.isNotEmpty(endArrivalTime)) {
            sql += " and t.first_visit_date <= '" + endArrivalTime + "'";
        }
        if (!"请选择".equals(oneChannel)) {
            if (StringUtil.isNotEmpty(oneChannel)) {
                sql += " and t.one_channel = '" + oneChannel + "'";
            }
        }
        if (!"请选择".equals(twoChannel)) {
            if (StringUtil.isNotEmpty(twoChannel)) {
                sql += " and t.two_channel = '" + twoChannel + "'";
            }
        }
        if (!"请选择".equals(thrChannel)) {
            if (StringUtil.isNotEmpty(thrChannel)) {
                sql += " and t.thr_channel = '" + thrChannel + "'";
            }
        }
        if (StringUtil.isNotEmpty(arrivalStore)) {
            sql += " and t1.arrival_store = '" + arrivalStore + "'";
        }
        if (StringUtil.isNotEmpty(reservationsNum)) {
            sql += " and t.reservations_num = '" + reservationsNum + "'";
        }
        if (StringUtil.isNotEmpty(wechatNumber)) {
            sql += " and t.wechat_number = '" + wechatNumber + "'";
        }
        sql+=" order by t1.get_time desc ) t1\n" +
                "        where t1.oneChannel!='老带新' and t1.twoChannel!='直接上门'" ;
        Map<String, Object> result = sqlMapper.selectOne(sql.toString());
        HashMap map = new HashMap();
        if (result != null) {
            map.put("borrowAmount_sum", result.get("borrowAmount_sum"));
        } else {
            map.put("borrowAmount_sum", "0");
        }
        return map;
    }

    @RequestMapping(value = "/customer_import")
    public String to_import(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "customer_import.html";
    }

}